package events {
	
	import org.flixel.FlxGroup;
	import org.flixel.FlxBasic;
	import org.flixel.FlxG;
	
	/*
	 * A basic game event system....
	 */
	public class GameEvent extends FlxBasic{
		
		private var excecutionCallback:Function;
		private var delay:Number, storedDelay:Number;
		private var recursiveCancel:Boolean;

		public function set timedelay(de:Number):void{
			delay = de;
			storedDelay = de;
		}

		public var parent:FlxGroup;
		public var condition:Function;
		public var dependencies:Array;
		public var done:Boolean;
		public var cancelled:Boolean;
		public var repetitions:int;
		public var uniqueID:String;
				
		public function GameEvent(excectutionCallback:Function, delay:Number = 0, condition:Function = null, repetitions:int = 0) {
			this.condition = condition;
			this.excecutionCallback = excectutionCallback;	
			this.delay = delay;
			this.storedDelay = delay;
			this.done = false;
			this.cancelled = false;
			this.recursiveCancel = false;
			this.repetitions = repetitions;
			this.dependencies = [];
			uniqueID = "none";
		}
		
		public function setUniqueID(id:String):GameEvent {
			this.uniqueID = id;
			return this;
		}
		
		override public function update():void {
			super.update();
			if (condition == null ? true : this.condition.length == 1 ? this.condition(this) : this.condition()){
				var dependanciesDone:Boolean = true;
				for (var i:uint = 0; i < dependencies.length; i++) {
					var dependancy:GameEvent = dependencies[i] as GameEvent;
					if (!dependancy.done){
						dependanciesDone = false;
					}
					if (dependancy.cancelled && dependancy.recursiveCancel){
						cancel(true);
						break;
					}
				}
				if (dependanciesDone){
					if (delay <= 0){
						if (excecutionCallback != null){
							if (excecutionCallback.length >= 1){
								excecutionCallback(this);
							}
							else {
								excecutionCallback();
							}
						}
						end();
					}
					else {
						delay -= FlxG.elapsed;
					}
				}
			}
		}
		
		public function addDependancy(gameEvent:GameEvent):void{
			this.dependencies.push(gameEvent);
		}
		
		public function cancel(recursiveCancel:Boolean):void {
			this.cancelled = true;
			this.recursiveCancel = recursiveCancel;
			this.repetitions = 0;
			end();
		}
		
		private function end():void {
			if (repetitions == 0){
				done = true;
				kill();
				if (this.parent != null){
					this.parent.remove(this);
				}
			}
			else {
				if(repetitions > 0){
					repetitions--;
				}
				this.delay = this.storedDelay;
				done = false;
			}
		}
	}
}
